import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import DashboardLayout from '../components/DashboardLayout.vue'
import WindowSettings from '../views/WindowSettings.vue'
import ScriptConfig from '../views/ScriptConfig.vue'
import UserManagement from '../views/UserManagement.vue'
import APKManagement from '../views/APKManagement.vue'

const routes = [
  {
    path: '/',
    redirect: '/dashboard/windows'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      requiresGuest: true // 需要未登录状态
    }
  },
  {
    path: '/dashboard',
    component: DashboardLayout,
    meta: {
      requiresAuth: true // 需要登录状态
    },
    children: [
      {
        path: '',
        redirect: '/dashboard/windows'
      },
      {
        path: 'windows',
        name: 'WindowSettings',
        component: WindowSettings
      },
      {
        path: 'scripts',
        name: 'ScriptConfig',
        component: ScriptConfig
      },
      {
        path: 'users',
        name: 'UserManagement',
        component: UserManagement
      },
      {
        path: 'apk',
        name: 'APKManagement',
        component: APKManagement
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const isLoggedIn = !!token

  // 需要登录的页面
  if (to.meta.requiresAuth && !isLoggedIn) {
    next('/login')
    return
  }

  // 需要未登录状态的页面（如登录页）
  if (to.meta.requiresGuest && isLoggedIn) {
    next('/dashboard')
    return
  }

  next()
})

export default router 